<template>
	<div class="address-panel">
		<button class="close-btn" @click="$emit('close')">×</button>
		<div class="title">配送至</div>
		<div class="content">
			<div class="item" v-for="(address, index) in addresses" :key="index" @click="selectAddress(address)">
				<div class="user">{{ address.contact }} {{ address.mobile }}</div>
				<div class="address">{{ address.province }}{{ address.city }}{{ address.town }}{{ address.street }}</div>
				<span :class="['icon', address.isDefault ? 'icon-checked' : 'icon-ring']"></span>
			</div>
		</div>
		<div class="footer">
			<div class="button primary">新建地址</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				addresses: [] // 初始地址数组为空，等待接口返回数据
			};
		},
		methods: {
			getAddressDetails() {
				// 请求地址详情
				this.$service({
					url: `/addresses`,
					method: 'GET'
				}).then(res => {
					if (res.code === 0) {
						// 将返回的地址数据更新到 addresses 列表
						this.addresses = res.data.map(address => ({
							contact: address.contact,
							mobile: address.mobile,
							province: address.province,
							city: address.city,
							town: address.town,
							street: address.street,
							isDefault: address.isDefault
						}));
					}
				});
			},
			selectAddress(address) {
				// 发送选中的地址到父组件
				this.$emit('select-address', address);
				// 关闭地址面板
				this.$emit('close');
			}
		},
		mounted() {
			this.getAddressDetails(); // 组件挂载时获取地址数据
		}
	};
</script>

<style scoped>
	.address-panel {
		padding: 0 30rpx;
		border-radius: 20rpx 20rpx 0 0;
		position: relative;
		background-color: #fff;
	}

	.close-btn {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		width: 60rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 50%;
		border: none;
		background-color: #f5f5f5;
		font-size: 40rpx;
		color: #999;
	}

	.title {
		line-height: 1;
		padding: 40rpx 0;
		text-align: center;
		font-size: 32rpx;
		font-weight: normal;
		border-bottom: 1rpx solid #ddd;
		color: #444;
	}

	.content {
		max-height: 60vh;
		overflow-y: auto;
		padding: 20rpx;
	}

	.item {
		padding: 30rpx 50rpx 30rpx 60rpx;
		background-size: 40rpx;
		background-repeat: no-repeat;
		background-position: 0 center;
		background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png);
		position: relative;
		margin-bottom: 20rpx;
	}

	.icon {
		font-size: 40rpx;
		position: absolute;
		top: 50%;
		right: 0;
		transform: translateY(-50%);
	}

	.icon-checked {
		color: #fdd300;
	}

	.icon-ring {
		color: #444;
	}

	.user {
		font-size: 28rpx;
		color: #444;
		font-weight: 500;
	}

	.address {
		font-size: 26rpx;
		color: #666;
		margin-top: 10rpx;
	}

	.footer {
		padding: 20rpx 0 40rpx;
	}

	.button {
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		margin: 0 20rpx;
		color: #fff;
		border-radius: 80rpx;
		font-size: 28rpx;
	}

	.primary {
		background-color: #fdd300;
	}
</style>
